#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2021/4/1 21:07 
# @Author : wenzi
# @File : api_cases.py 
# @Software: PyCharm
import json
import time

from apiRestful.extensions import db
from flask import request, jsonify
from flask_restful import Api

from . import api_bp
from apiRestful.utils import log_util
from apiRestful.models.case import Cases
from apiRestful.utils.cors_utils import TabrResource
from .api_auth import login_required
import math

api_case = Api(api_bp)
logger = log_util.log


class AddTextCaseApi(TabrResource):

    @login_required
    def post(self):
        logger.debug('AddTextCaseApi.post.url = ' + str(request.url))
        raw_data = request.get_data(as_text=True)
        case_info = json.loads(raw_data)
        logger.debug('AddTextCaseApi.post.case_info = ' + str(case_info))
        if not case_info['caseName']:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: Miss require params!'
            response = jsonify({'msg': reason})
        else:
            c = Cases.query.filter_by(caseName=case_info['caseName']).first()
            if c is None:
                try:
                    c = Cases(caseName=case_info['caseName'])
                    c.caseData = case_info['caseData']
                    c.caseType = 'text'
                    c.remark = case_info['remark']
                    db.session.add(c)
                    db.session.commit()
                except Exception as e:
                    logger.error(e)
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} failure...'
                    db.session.rollback()
                    response = jsonify({'msg': reason})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} success...'
                    response = jsonify({'msg': reason})
                finally:
                    db.session.close()
            else:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} failure,because caseName has used....'
                db.session.rollback()
                response = jsonify({'msg': reason})
        logger.debug('AddTextCaseApi.post.response = ' + response.get_data(as_text=True))
        return response


class AddFileCaseApi(TabrResource):

    @login_required
    def post(self):
        logger.debug('AddFileCaseApi.post.url = ' + str(request.url))
        case_name = request.form.get('caseName')
        remark = request.form.get('remark')
        file = request.files.get('caseFile')
        logger.debug('AddFileCaseApi.caseName = ' + str(case_name))
        if not case_name:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: Miss require params!'
            response = jsonify({'msg': reason})
        else:
            c = Cases.query.filter_by(caseName=case_name).first()
            if c is None:
                try:
                    c = Cases(caseName=case_name)
                    c.caseData = file.read().decode()
                    c.caseType = 'file'
                    c.remark = remark
                    db.session.add(c)
                    db.session.commit()
                except Exception as e:
                    logger.error(e)
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_name} failure...'
                    db.session.rollback()
                    response = jsonify({'msg': reason})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_name} success...'
                    response = jsonify({'msg': reason})
                finally:
                    db.session.close()
            else:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_name} failure,because username has used....'
                db.session.rollback()
                response = jsonify({'msg': reason})
        logger.debug('AddFileCaseApi.post.response = ' + response.get_data(as_text=True))
        return response


class DelCaseApi(TabrResource):

    @login_required
    def post(self):
        logger.debug('DelCaseApi.post.url = ' + str(request.url))
        raw_data = request.get_data(as_text=True)
        case_info = json.loads(raw_data)
        logger.debug('DelCaseApi.post.case_info = ' + str(case_info))
        if not case_info['caseName']:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case delete: Miss require params!'
            response = jsonify({'msg': reason})
        else:
            c = Cases.query.filter_by(caseName=case_info['caseName']).first()
            if c is None:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case delete: Case is not exist!'
                response = jsonify({'msg': reason})
            else:
                try:
                    db.session.delete(c)
                    db.session.commit()
                except Exception as e:
                    logger.error(e)
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case delete: {case_info["caseName"]} failure...'
                    db.session.rollback()
                    response = jsonify({'msg': reason})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case delete: {case_info["caseName"]} success...'
                    response = jsonify({'msg': reason})
                finally:
                    db.session.close()
        logger.debug('DelCaseApi.post.response = ' + response.get_data(as_text=True))
        return response


class ModifyCaseApi(TabrResource):

    @login_required
    def post(self):
        logger.debug('ModifyCaseApi.post.url = ' + str(request.url))
        raw_data = request.get_data(as_text=True)
        case_info = json.loads(raw_data)
        logger.debug('ModifyCaseApi.post.case_info = ' + str(case_info))
        if not case_info['caseName']:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case modify: Miss require params!'
            response = jsonify({'msg': reason})
        else:
            c = Cases.query.filter_by(caseName=case_info['caseName']).first()
            if c is None:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case modify: Case is not exist!'
                response = jsonify({'msg': reason})
            else:
                try:
                    c.caseData = case_info['caseData']
                    c.remark = case_info['remark']
                    db.session.commit()
                except Exception as e:
                    logger.error(e)
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case modify: {case_info["caseName"]} failure...'
                    db.session.rollback()
                    response = jsonify({'msg': reason})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case modify: {case_info["caseName"]} success...'
                    response = jsonify({'msg': reason})
                finally:
                    db.session.close()
        logger.debug('ModifyCaseApi.post.response = ' + response.get_data(as_text=True))
        return response


class QueryCaseApi(TabrResource):

    @login_required
    def get(self):
        page = request.args.get('pageNum', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        all_items = Cases.query.paginate(page, page_size)
        all_datas = bedict(all_items.items)
        logger.debug('QueryCaseApi.datas = ' + str(all_datas))
        return jsonify(all_datas)


class GetCasePages(TabrResource):

    @login_required
    def get(self):
        page_size = request.args.get('pageSize', 10, type=int)
        all_items_count = Cases.query.count()
        total_pages = math.ceil(all_items_count / page_size)
        data = {
            'total_cases': all_items_count,
            'total_pages': total_pages
        }
        logger.debug('GetCasePagesApi.datas = ' + str(data))
        return jsonify(data)


def bedict(a):
    lic = []
    for item in a:
        lic.append(
            {
                'caseName': item.caseName,
                'caseData': item.caseData,
                'remark': item.remark,
                'caseType': item.caseType,
                'id': item.id
            }
        )
    return lic


api_case.add_resource(AddTextCaseApi, '/testCase/text', endpoint='add_text_case')
api_case.add_resource(AddFileCaseApi, '/testCase/file', endpoint='add_file_case')
api_case.add_resource(DelCaseApi, '/testCase/delete', endpoint='del_case')
api_case.add_resource(GetCasePages, '/testCase/total', endpoint='case_total')
api_case.add_resource(QueryCaseApi, '/testCase/list', endpoint='case_list')
api_case.add_resource(ModifyCaseApi, '/testCase/modify', endpoint='case_modify')
